<template>
	<view class="content">
		<view class="mess" v-if="checkInfo == false">
			<view class="article">
				您已经完成实名了
			</view>
		</view>
		<view v-if="checkInfo == true">
			<view class="uni-input">
				姓名：<input type="text" v-model="userFrom.name" />
			</view>
			<view class="uni-input">
				证件号码：<input type="text" v-model="userFrom.id_number" />
			</view>
			<picker @change="bindPickerChange" :value="userFrom.leixingIndex"
				:range="userFrom.leixingData.map(item => item.name)">
				<view class="uni-input">证件类型：{{ userFrom.leixingData[userFrom.leixingIndex].name }}</view>
			</picker>
		</view>
		<view v-if="checkInfo == true" class="btn" @click="confirmSubmit">
			确认提交
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from 'vue';
	import {
		getShiming,
		checkUserShiming
	} from '@/api/mine_api.js';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	// 判断是否需要显示无内容
	const checkInfo = ref(true)


	// 用户表单数据
	const userFrom = reactive({
		openid: '', // 用户openid
		id_number: '', // 身份证号
		leixing: 'IDENTITY_CARD', // 身份证类型
		name: '', // 用户姓名
		leixingIndex: 0, // 当前选中的身份证类型索引
		leixingData: [ // 可选身份证类型数据
			{
				name: '大陆身份证',
				num: 'IDENTITY_CARD'
			}
			// },
			// {
			// 	name: '华侨护照',
			// 	num: '414'
			// },
			// {
			// 	name: '港澳居民来往内地通行证',
			// 	num: '516'
			// },
			// {
			// 	name: '外国人永久居留身份证',
			// 	num: '553'
			// },
			// {
			// 	name: '台湾居民来往大陆通行证、台胞证',
			// 	num: '511'
			// }
		]
	});

	// 更新选择的身份证类型
	const bindPickerChange = (event) => {
		userFrom.leixingIndex = event.detail.value;
		userFrom.leixing = userFrom.leixingData[userFrom.leixingIndex].num;
	};

	// 提交按钮点击事件
	const confirmSubmit = () => {
		if (!userFrom.name || !userFrom.id_number) {
			uni.showToast({
				title: '请填写完整信息',
				icon: 'none'
			});
			return;
		}

		// 执行实名认证请求
		_getShiming();
	};

	const _getShiming = () => {
		let data = {
			openid: userFrom.openid,
			shenfenzheng: userFrom.id_number,
			leixing: userFrom.leixing,
			name: userFrom.name
		};

		// 1. 身份证号长度必须为18位
		if (data.shenfenzheng.length !== 18) {
			console.log('身份证号长度必须为18位');
			uni.showModal({
				title:'提示',
				content:'身份证长度不足'
			})
			
			return; // 如果长度不对，直接返回
		}

		// 2. 身份证号前17位必须为数字，且最后一位为数字或字母X
		const idRegex = /^\d{17}(\d|X)$/;
		if (!idRegex.test(data.shenfenzheng)) {
			console.log('身份证号格式不正确');
			uni.showModal({
				title:'提示',
				content:'身份证格式验证不通过'
			})
			return; // 如果格式不正确，直接返回
		}

		// 3. 校验出生日期（第7-14位）是否合法
		const birthDate = data.shenfenzheng.substring(6, 14);
		const birthYear = parseInt(birthDate.substring(0, 4), 10);
		const birthMonth = parseInt(birthDate.substring(4, 6), 10);
		const birthDay = parseInt(birthDate.substring(6, 8), 10);

		// 日期合法性检查
		const isValidDate = (year, month, day) => {
			const date = new Date(year, month - 1, day);
			return date.getFullYear() === year && date.getMonth() + 1 === month && date.getDate() === day;
		};

		if (!isValidDate(birthYear, birthMonth, birthDay)) {
			console.log('身份证号中的出生日期不合法');
			uni.showModal({
				title:'提示',
				content:'身份证出生日验证不通过'
			})
			return; // 如果日期不合法，直接返回
		}

		// 4. 校验位校验
		const checkCode = '10X98765432';
		const coefficient = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

		let sum = 0;
		for (let i = 0; i < 17; i++) {
			sum += parseInt(data.shenfenzheng.charAt(i), 10) * coefficient[i];
		}
		const calculatedCheckCode = checkCode.charAt(sum % 11);

		if (data.shenfenzheng.charAt(17).toUpperCase() !== calculatedCheckCode) {
			console.log('身份证号的校验位不正确');
			uni.showModal({
				title:'提示',
				content:'身份证校验位不通过'
			})
			return; // 如果校验位不对，直接返回
		}

		console.log('身份证号验证通过');
		console.log(userFrom);

		getShiming(data).then((res) => {
		    uni.showModal({
		        title: res.result,
		        content: res.name
		    })
		})
	};


	// 获取用户有没有实名
	const _getUserCheck = (id) => {
		checkUserShiming(id).then((res) => {
			console.log(res);
			if (res.result == '已实名') {
				checkInfo.value = false
			} else if (res.result == '未实名') {
				checkInfo.value = true
			}
		})
	}

	onLoad(() => {
		uni.getStorage({
			key: 'openid',
			success(res) {
				userFrom.openid = res.data.openid
				_getUserCheck(res.data.openid)
			}
		})
	})
</script>

<style lang="scss" scoped>
	.content {
		padding: 40px 20px;

		.mess {
			text-align: center;
			min-height: calc(100vh - 80px);
			display: flex;
			justify-content: center;
			flex-direction: column;

			.article {}
		}

		.uni-input {
			display: flex;
			padding: 10px;
			border-bottom: 1px solid #ccc;
			border-radius: 5px;
		}
	}

	.btn {
		background-color: #007aff;
		color: white;
		padding: 10px;
		text-align: center;
		border-radius: 5px;
		margin-top: 20px;
	}
</style>